package com.sakila.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import com.sakila.dao.AddressDao;
import com.sakila.dao.RoleDao;
import com.sakila.dao.StaffDao;
import com.sakila.dao.StoreDao;
import com.sakila.jaas.RoleDefinition;
import com.sakila.pojo.Role;
import com.sakila.pojo.Staff;
import com.sakila.pojo.Store;
import com.sakila.pojo.other.Page;
import com.sakila.service.StaffService;

@Service
public class StaffServiceImpl implements StaffService {
	@Resource
	private StaffDao staffDao;
	@Resource
	private StoreDao storeDao;
	@Resource
	private AddressDao addressDao;
	@Resource
	private RoleDao roleDao;
	
	@Override
	public boolean isManager(Staff staff) {
		return storeDao.findByStaff(staff) == null ? false : true;
	}

	public List<Staff> viewSubStaffs(Staff staff) {
		List<Role> roles = new ArrayList<Role>();
		roles.add(new Role(RoleDefinition.ROLE_ADMIN));		
		
		for(Role role : staff.getRoles()){
			if(role.getRole().equals(RoleDefinition.ROLE_ADMIN)){
				return staffDao.findByHasNotRoles(null, roles);
			}
		}
		
		roles.add(new Role(RoleDefinition.ROLE_MANAGER));
		return staffDao.findByHasNotRoles(staff.getStore(), roles);
	}
	
	@Override
	public Staff findByUsername(String username) {
		Staff staff = new Staff();
		staff.setUsername(username);
		List<Staff> list = staffDao.findByProperties(staff);
		if(list.size() == 0){
			return null;
		}
		return list.get(0);
	}

	@Override
	public Staff findById(Integer id) {
		return staffDao.findByPk(id);
	}

	@Override
	public void saveStaff(Staff staff) {
		staff.setActive(1);
		Set<Role> roles = new HashSet<Role>();
		roles.add(new Role(RoleDefinition.ROLE_STAFF));
		staff.setRoles(roles);
		
		addressDao.save(staff.getAddress());
		staffDao.save(staff);
		roleDao.saveStaffRoles(staff);
	}

	@Override
	public void saveManager(Staff staff) {
		staff.setActive(1);
		Set<Role> roles = new HashSet<Role>();
		roles.add(new Role(RoleDefinition.ROLE_STAFF));
		roles.add(new Role(RoleDefinition.ROLE_MANAGER));
		staff.setRoles(roles);
		
		addressDao.save(staff.getAddress());
		staffDao.save(staff);
	}
	
	@Override
	public void update(Staff staff) {
		staffDao.update(staff);
	}

	@Override
	public List<Staff> findAll(Page page) {
		return staffDao.findAll(page);
	}

	@Override
	public void setStoreManager(Staff staff) {
		Staff previousManager = storeDao.findManager(staff.getStore());
		roleDao.delete(new Role(previousManager, RoleDefinition.ROLE_MANAGER));
		
		roleDao.save(new Role(staff, RoleDefinition.ROLE_MANAGER));
		Store store = staff.getStore();
		store.setManager(staff);
		storeDao.save(store);
	}

}
